package com.aiyige.page.my.customer;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.eventbus.EventCustomerChanged;
import com.aiyige.base.eventbus.EventCustomerFollowupAddSuccess;
import com.aiyige.model.CustomerListEntity;
import com.aiyige.model.CustomerRequestModel;
import com.aiyige.model.request.GetCustomerListRequest;
import com.aiyige.model.response.CustomerListResponse;
import com.aiyige.page.my.customer.adapter.CustomerManageListAdapter;
import com.aiyige.page.my.customer.dialog.DialogCustomerScreen;
import com.aiyige.page.my.customer.model.CustomerEntity;
import com.aiyige.page.my.customer.model.CustomerFilter;
import com.aiyige.page.my.customer.model.CustomerFollowupEntity;
import com.aiyige.page.my.customer.model.CustomerScreenChildEntity;
import com.aiyige.page.my.customer.model.CustomerSort;
import com.aiyige.page.my.customer.model.CustomerType;
import com.aiyige.track.annotation.Track;
import com.aiyige.utils.HighLightWordUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.widget.CommonDataView;
import com.aiyige.utils.widget.MyEditText;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSONObject;
import com.vondear.rxtools.RxEncodeTool;
import com.vondear.rxtools.RxKeyboardTool;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * Created by xiachao on 2018/3/21.
 */
@Track("客户管理列表")
@Route(path = ARouterConfig.CustomerManagementListPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class CustomerManagementListPage extends BaseActivity implements DialogCustomerScreen.CallBack, CommonDataView.RetrofitStub {


    List<CustomerEntity> list = new ArrayList<>();
    @BindView(R.id.title_layout)
    View titleLayout;

    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.iv_screen)
    ImageView ivScreen;
    @BindView(R.id.cancelLayout)
    ExpandableLayout cancelLayout;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.et_search)
    MyEditText myEditText;
    @BindView(R.id.hintLayout)
    RelativeLayout hintLayout;
    @BindView(R.id.searchBox)
    RelativeLayout searchBox;
    @BindView(R.id.tv_sort_add_time)
    TextView tvSortAddTime;
    @BindView(R.id.rl_sort_add_time)
    RelativeLayout rlSortAddTime;
    @BindView(R.id.tv_sort_consume)
    TextView tvSortConsume;// 总消费
    @BindView(R.id.rl_sort_consume)
    RelativeLayout rlSortConsume;
    @BindView(R.id.tv_sort_lately_goto_class)
    TextView tvSortLastSchooltime;
    @BindView(R.id.tv_sort_lately_follow_up)
    TextView tvSortLastFollowUp;
    @BindView(R.id.tv_sort_next_follow_up)
    TextView tvSortNextFollowUp;
    @BindView(R.id.cdv)
    CommonDataView cdv;


    CustomerManageListAdapter adapter;
    private final static int MSG_WORK = 0x01;


    // 客户类型
    private String listType = CustomerType.ALL_CUSTOMER;


    // 排序
    private String listSort = CustomerSort.ADD_TIME_DOWN;
    HandlerThread handlerThread;
    Handler requestDataHandler;

    List<CustomerScreenChildEntity> screenList = new ArrayList<>();

    CustomerFilter customerFilter;

    DialogCustomerScreen screenDialog;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_customer_management_list);
        ButterKnife.bind(this);
        if (handlerThread == null) {
            handlerThread = new HandlerThread("requestList");
        }
        handlerThread.start();
        requestDataHandler = new Handler(handlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                doRequest();
            }
        };
        setAutoRegisterEventBus(true);
        initView();
        refreshData();
    }

    private void initView() {
        myEditText.setActionSearch(new MyEditText.ActionCallback() {
            @Override
            public void actionSearch(String value) {
                refreshData();
            }
        });
        myEditText.setEditTextHint(getString(R.string.search));
        myEditText.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s != null) {//此逻辑是用于修复： 编辑状态，用户输入了没有内容的搜索结果，当用户删除关键字后，还原到原来的内容
                    String value = s.toString();
                    if (isEmpty(value)) {
                        refreshData();
                    }
                }
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
//        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new CustomerManageListAdapter();
//        recyclerView.setAdapter(adapter);
//        recyclerView.addItemDecoration(new MyRecyclerViewDivider(
//                this, LinearLayoutManager.VERTICAL, UIHelper.dip2px(this, 1), R.color.zwcolor_gray_e3e3e3));
//        recyclerView.setBackgroundColor(ContextCompat.getColor(this, R.color.zwcolor_gray_f4f8f9));
        cdv.config(adapter, this);
        cdv.addItemDecoration(10, R.color.zwcolor_gray_e3e3e3);
        cdv.setRecyclerViewBgColor(ContextCompat.getColor(this, R.color.zwcolor_gray_f4f8f9));
        cdv.setActionCallback(new CommonDataView.UserActionCallback() {
            @Override
            public void onUserRefresh() {
                refreshData();
            }

            @Override
            public void onUserLoadMore() {

            }
        });
        setListSort(getListSort());
    }

    /**
     * 多线程只执行最后线程
     */
    private void refreshData() {
//        makeData();
        requestDataHandler.removeMessages(MSG_WORK);
        requestDataHandler.sendEmptyMessage(MSG_WORK);
    }

    /**
     * 执行请求
     */
    private void doRequest() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                cdv.doRefreshRequest();
                if (!TextUtils.isEmpty(getKeyWork())) {
                    RxKeyboardTool.hideSoftInput(CustomerManagementListPage.this);
                }
            }
        });

//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                adapter.replaceData(list);
//                cdv.hideCoverLayout();
//                cdv.clearRequestState();
//                adapter.loadMoreComplete();
//            }
//        });
    }


    private void showScreenDialog() {
        if (screenDialog == null) {
            screenDialog = new DialogCustomerScreen(this, getListType(), this);
        } else {
            screenDialog.setCurrentType(getListType());
        }
        if (screenDialog.isShowing()) {
            screenDialog.dismiss();
        } else {
            screenDialog.showAsDropDown(titleLayout);
        }
//        DialogCustomerScreen.showAsDropDown(CustomerManagementListPage.this, getListType(), titleLayout, this);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 1) {
            screenList = data.getParcelableArrayListExtra("list");
            refreshData();
        }
        else if (resultCode == RESULT_OK && requestCode == 2) {
            CustomerEntity customerEntity = data.getParcelableExtra("customerEntity");
            if (customerEntity != null) {

            }
            refreshData();
        }
    }

    @OnClick({R.id.titleBackBtn, R.id.iv_title, R.id.titleTv, R.id.iv_screen, R.id.et_search, R.id.tv_sort_add_time, R.id.rl_sort_add_time, R.id.tv_sort_consume, R.id.rl_sort_consume, R.id.tv_sort_lately_goto_class, R.id.tv_sort_lately_follow_up, R.id.tv_sort_next_follow_up})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.iv_title:
            case R.id.titleTv:
                showScreenDialog();
                break;
            case R.id.iv_screen:
                ARouter.getInstance().build(ARouterConfig.CustomerScreenPage)
                        .withParcelableArrayList("topList", (ArrayList<? extends Parcelable>) screenList)
                        .navigation(this, 1);
                break;
            case R.id.et_search:
                break;
            case R.id.rl_sort_add_time:
            case R.id.tv_sort_add_time:
                setListSort(getListSort().equals(CustomerSort.ADD_TIME_DOWN)
                        ? CustomerSort.ADD_TIME_UP : CustomerSort.ADD_TIME_DOWN);
                break;
            case R.id.tv_sort_consume:
            case R.id.rl_sort_consume:
                setListSort(getListSort().equals(CustomerSort.TOTAL_CONSUMPTION_DOWN)
                        ? CustomerSort.TOTAL_CONSUMPTION_UP : CustomerSort.TOTAL_CONSUMPTION_DOWN);
                break;
            case R.id.tv_sort_lately_goto_class:
                setListSort(CustomerSort.LATELY_GOTO_CLASS);
                break;
            case R.id.tv_sort_lately_follow_up:
                setListSort(CustomerSort.LATELY_FOLLOW_UP);
                break;
            case R.id.tv_sort_next_follow_up:
                setListSort(CustomerSort.NEXT_FOLLOW_UP);
                break;
        }
    }


    public String getListType() {
        return listType;
    }

    public void setListType(String listType) {
        this.listType = listType;
        titleTv.setText(CustomerType.getName(listType));
    }

    public String getListSort() {
        return listSort;
    }

    public void setListSort(String listSort) {
        this.listSort = listSort;
        Drawable drawableNormal = getResources().getDrawable(R.drawable.customer_order_normal);
        drawableNormal.setBounds(0, 0, drawableNormal.getIntrinsicWidth(), drawableNormal.getIntrinsicHeight());
        tvSortAddTime.setCompoundDrawables(null, null, drawableNormal, null);
        tvSortConsume.setCompoundDrawables(null, null, drawableNormal, null);
        Drawable drawableDown = getResources().getDrawable(R.drawable.customer_order_selected_down);
        drawableDown.setBounds(0, 0, drawableNormal.getIntrinsicWidth(), drawableNormal.getIntrinsicHeight());
        Drawable drawableUp = getResources().getDrawable(R.drawable.customer_order_selected_up);
        drawableUp.setBounds(0, 0, drawableNormal.getIntrinsicWidth(), drawableNormal.getIntrinsicHeight());

        tvSortAddTime.setSelected((listSort.equals(CustomerSort.ADD_TIME_DOWN)||listSort.equals(CustomerSort.ADD_TIME_UP)));
        tvSortConsume.setSelected((listSort.equals(CustomerSort.TOTAL_CONSUMPTION_UP)||listSort.equals(CustomerSort.TOTAL_CONSUMPTION_DOWN)));
        if (listSort.equals(CustomerSort.ADD_TIME_DOWN)) {
            tvSortAddTime.setCompoundDrawables(null, null, drawableDown, null);

        } else if (listSort.equals(CustomerSort.ADD_TIME_UP)) {
            tvSortAddTime.setCompoundDrawables(null, null, drawableUp, null);
        } else if (listSort.equals(CustomerSort.TOTAL_CONSUMPTION_UP)) {
            tvSortConsume.setCompoundDrawables(null, null, drawableUp, null);
        } else if (listSort.equals(CustomerSort.TOTAL_CONSUMPTION_DOWN)) {
            tvSortConsume.setCompoundDrawables(null, null, drawableDown, null);
        }
        tvSortLastSchooltime.setSelected(listSort.equals(CustomerSort.LATELY_GOTO_CLASS));//最近上课
        tvSortLastFollowUp.setSelected(listSort.equals(CustomerSort.LATELY_FOLLOW_UP));//最近跟进
        tvSortNextFollowUp.setSelected(listSort.equals(CustomerSort.NEXT_FOLLOW_UP));//下次跟进
        refreshData();
    }

    @Override
    public void selectedCallback(String type) {
        setListType(type);
        refreshData();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (requestDataHandler != null) {
            requestDataHandler.removeMessages(MSG_WORK);
        }
        if (handlerThread != null) {
            handlerThread.quit();
        }
    }

    private String getKeyWork() {
        String value = myEditText.getValue();
        return (value == null || value.equals(""))?null:value;
    }

    private String getFilters() {
        if (!ListUtil.isEmpty(screenList)) {
            customerFilter = new CustomerFilter();
            List<String> list = new ArrayList<>();
            for (CustomerScreenChildEntity customerEntity : screenList) {
                list.add(customerEntity.getId());
            }
            customerFilter.setCourseIds(list);
            return RxEncodeTool.urlEncode(JSONObject.toJSONString(customerFilter));
//            return JSONObject.toJSONString(customerFilter);
        }
        return null;
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        return GetCustomerListRequest.newBuilder().keyWord(getKeyWork()).type(listType).order_engine(listSort).filters(getFilters()).pageNum(currentPage + "").build();
    }



    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        String respJsonTest = respJson;
        Log.v("XiachaoTest", respJsonTest);
        try {
            CustomerListResponse homeResponse = JsonUtil.toObject(respJson, CustomerListResponse.class);
            if (ListUtil.isEmpty(homeResponse.getContent())) {
                resultList.addAll(homeResponse.getContent());
                return new CommonDataView.HandleResult(homeResponse.isLast());
            } else {
                List<CustomerListEntity> responseList = homeResponse.getContent();
                List<CustomerEntity> list = new ArrayList<>();

                for (CustomerListEntity customerListEntity : responseList) {
                    list.add(CustomerEntity.newBuilder()
                            .id(customerListEntity.getId())
                            .avatar(customerListEntity.getAvatar())
                            .customerFrom(customerListEntity.getFromChannel())
                            .customerType(customerListEntity.getType())
                            .lastFollowupTime(customerListEntity.getFollowupTime())
                            .name(HighLightWordUtil.highLight(customerListEntity.getName(), getKeyWork()))
                            .nextFollowupTime(customerListEntity.getNextFollowupTime())
                            .phone(customerListEntity.getMobile())
                            .remark(customerListEntity.getRemark())
                            .sex(customerListEntity.getSex())
                            .totalTransactionOrderCount(customerListEntity.getDealCount())// 这里存在疑虑
                            .totalTransactionPrice(customerListEntity.getTotalConsume())// 这里存在疑虑
                            .buyerId(customerListEntity.getBuyerId())
                            .build());
                }
                resultList.addAll(list);
                return new CommonDataView.HandleResult(homeResponse.isLast());
            }

        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }

    /**
     * 用户编辑后刷新页面
     *
     * @param customerChanged
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventCustomerChanged(EventCustomerChanged customerChanged) {
        if (customerChanged != null && customerChanged.getCustomerRequestModel() != null) {
            CustomerRequestModel customerRequestModel = customerChanged.getCustomerRequestModel();
            if (!ListUtil.isEmpty(adapter.getData())) {
                for (CustomerEntity customerEntity : adapter.getData()) {
                    if (customerEntity.getId().equals(customerRequestModel.getId())) {
                        customerEntity.setName(customerRequestModel.getName());
                        customerEntity.setCustomerType(customerRequestModel.getType());
                        customerEntity.setCustomerFrom(customerRequestModel.getFromChannel());
                        customerEntity.setPhone(customerRequestModel.getMobile());
                        customerEntity.setRemark(customerRequestModel.getRemark());
                        customerEntity.setSex(customerRequestModel.getSex());
                        adapter.notifyDataSetChanged();
                        break;
                    }
                }
            }
        }
    }

    /**
     * 用户编辑后刷新页面
     * @param eventCustomerFollowupAddSuccess
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventCustomerFollowupAddSuccess(EventCustomerFollowupAddSuccess eventCustomerFollowupAddSuccess) {
        CustomerFollowupEntity followupEntity = eventCustomerFollowupAddSuccess.getCustomerFollowupEntity();
        if (followupEntity != null) {
            if (!ListUtil.isEmpty(adapter.getData())) {
                for (CustomerEntity customerEntity : adapter.getData()) {
                    if (!TextUtils.isEmpty(customerEntity.getId()) && !TextUtils.isEmpty(followupEntity.getCustomerId())
                            && customerEntity.getId().equals(followupEntity.getCustomerId())) {
                        customerEntity.setFollowupTime(followupEntity.getNearestFollowupTime()+"");
                        customerEntity.setNextFollowupTime(followupEntity.getNearestNextFollowupTime()+"");
                        adapter.notifyDataSetChanged();
                        break;
                    }
                }
            }
        }
    }

}
